package com.stone.framework.core.mybatis;

import java.time.LocalDateTime;

import org.apache.ibatis.reflection.MetaObject;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.stone.framework.core.context.UserContext;

/**
 * 使用mybatis-plus自动填充功能需注入该Bean，否则不生效
 * 
 * @author whocares
 * @date 2020/04/16
 */
public class CommonEntityMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createDate", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "createUser", String.class, UserContext.getDefaultUsername());
        this.strictInsertFill(metaObject, "updateDate", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateUser", String.class, UserContext.getDefaultUsername());
        this.strictInsertFill(metaObject, "version", Long.class, 0L);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // this.strictUpdateFill(metaObject, "updateDate", LocalDateTime.class, LocalDateTime.now());
        // this.strictUpdateFill(metaObject, "updateUser", String.class, UserContext.getDefaultUsername());

        // updateDate & updateUser 无论metaObject 是否为null都更新
        this.setFieldValByName("updateDate", LocalDateTime.now(), metaObject);
        this.setFieldValByName("updateUser", UserContext.getDefaultUsername(), metaObject);
    }

}
